<template>
  <view class="container">
    <view class="header">
      <text class="header-title">编辑个人资料</text>
      <view class="header-right" @click="saveProfile">保存</view>
    </view>
    
    <!-- 头像编辑 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="chooseAvatar">
        <image :src="formData.avatar" mode="aspectFill" class="avatar"></image>
        <view class="avatar-edit-mask">
          <uni-icons type="camera" size="24" color="#fff"></uni-icons>
          <text class="avatar-edit-text">更换头像</text>
        </view>
      </view>
    </view>
    
    <!-- 个人信息表单 -->
    <view class="form-section">
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input type="text" v-model="formData.nickname" class="form-input" placeholder="请输入昵称" />
      </view>
      
      <view class="form-item">
        <text class="form-label">手机号</text>
        <text class="form-value">{{ formData.phonenumber }}</text>
      </view>
      
      <view class="form-item">
        <text class="form-label">邮箱</text>
        <input type="text" v-model="formData.email" class="form-input" placeholder="请输入邮箱" />
      </view>
    </view>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo, uploadAvatar } from '@/api/user'
import config from '@/common/config'

export default {
  data() {
    return {
      formData: {
        nickname: '',
        phonenumber: '',
        email: '',
        avatar: '/static/images/user-avatar.png'
      },
      uploading: false,
      tempAvatarPath: null // 存储临时头像路径
    };
  },
  onLoad() {
    this.loadUserInfo();
  },
  methods: {
    // 加载用户信息
    async loadUserInfo() {
      try {
        console.log('开始加载用户信息');
        const res = await getUserInfo();
        console.log('获取用户信息结果:', res);
        
        if (res.code === 200 && res.data) {
          const userData = res.data.user || res.data;
          console.log('用户数据:', userData);
          
          // 处理头像URL
          let avatar = userData.avatarUrl || userData.avatar || '/static/images/user-avatar.png';
          console.log('原始头像URL:', avatar);
          
          // 确保avatar是字符串类型
          if (typeof avatar !== 'string') {
            avatar = '/static/images/user-avatar.png';
          }
          
          // 只对非静态资源的相对路径进行拼接
          if (avatar && avatar.startsWith('/') && !avatar.startsWith('/static/')) {
            avatar = config.baseUrl + avatar;
          }
          console.log('处理后的头像URL:', avatar);
          
          this.formData = {
            nickname: userData.nickname || userData.nickName || '',
            phonenumber: userData.phonenumber || userData.phoneNumber || '',
            email: userData.email || '',
            avatar: avatar
          };
          console.log('表单数据初始化完成');
        }
      } catch (error) {
        console.error('加载用户信息失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 选择头像
    chooseAvatar() {
      uni.showActionSheet({
        itemList: ['拍照', '从相册选择'],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.uploadImage('camera');
          } else if (res.tapIndex === 1) {
            this.uploadImage('album');
          }
        }
      });
    },
    
    // 选择图片（只在本地预览，不上传）
    uploadImage(sourceType) {
      if (this.uploading) return;
      
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: [sourceType],
        success: (chooseResult) => {
          const tempFilePath = chooseResult.tempFilePaths[0];
          console.log('选择的临时图片路径:', tempFilePath);
          
          // 保存临时路径，用于后续上传
          this.tempAvatarPath = tempFilePath;
          
          // 在UI上直接显示本地图片（预览效果）
          this.formData.avatar = tempFilePath;
          
          uni.showToast({
            title: '头像已选择，点击保存后生效',
            icon: 'none'
          });
        }
      });
    },
    
    // 保存个人资料
    async saveProfile() {
      // 简单的表单验证
      if (!this.formData.nickname.trim()) {
        return uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
      }
      
      if (this.formData.email && !/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(this.formData.email)) {
        return uni.showToast({
          title: '请输入有效的邮箱',
          icon: 'none'
        });
      }
      
      try {
        // 1. 如果有新选择的头像，先上传头像
        if (this.tempAvatarPath) {
          this.uploading = true;
          console.log('开始上传头像...');
          
          // 调用uploadAvatar方法上传头像到后端
          const avatarRes = await uploadAvatar(this.tempAvatarPath);
          
          if (avatarRes.code !== 200 || !avatarRes.data) {
            throw new Error(avatarRes.msg || '头像上传失败');
          }
          
          console.log('头像上传成功:', avatarRes);
          // 保存上传后的头像URL
          let avatarUrl = avatarRes.data.imgUrl;
          
          // 如果返回的是相对路径，则拼接baseUrl
          if (avatarUrl && avatarUrl.startsWith('/') && !avatarUrl.startsWith('/static/')) {
            this.formData.avatar = config.baseUrl + avatarUrl;
          } else {
            this.formData.avatar = avatarUrl;
          }
          
          // 清除临时路径标记
          this.tempAvatarPath = null;
        }
        
        // 2. 构建请求数据更新用户信息
        const requestData = {
          nickname: this.formData.nickname,
          email: this.formData.email
        };
        
        // 处理头像路径 - 确保只存储相对路径
        if (this.formData.avatar && typeof this.formData.avatar === 'string') {
          if (this.formData.avatar.startsWith(config.baseUrl)) {
            // 从完整URL中提取相对路径
            requestData.avatar = this.formData.avatar.replace(config.baseUrl, '');
          } else if (this.formData.avatar.startsWith('/') && !this.formData.avatar.startsWith('/static/')) {
            // 已经是相对路径
            requestData.avatar = this.formData.avatar;
          }
          // 注意：静态资源路径不保存到数据库
        }
        
        console.log('保存个人资料请求数据:', requestData);
        const res = await updateUserInfo(requestData);
        
        if (res.code === 200) {
          // 更新成功，清除缓存并返回
          uni.removeStorageSync('UserInfo');
          
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
          
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || '保存失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('保存个人资料失败:', error);
        uni.showToast({
          title: error.message || '保存失败，请重试',
          icon: 'none'
        });
      } finally {
        this.uploading = false;
      }
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.header-right {
  font-size: 16px;
  color: #36D;
}

.avatar-section {
  display: flex;
  justify-content: center;
  padding: 30px 0;
  background-color: #fff;
  margin-bottom: 10px;
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.avatar-edit-mask {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 5px;
  border-radius: 0 0 50% 50%;
  opacity: 0.8;
}

.avatar-edit-text {
  font-size: 12px;
  color: #fff;
  margin-top: 2px;
}

.form-section {
  background-color: #fff;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 80px;
  font-size: 16px;
  color: #666;
}

.form-input {
  flex: 1;
  font-size: 16px;
  color: #333;
  padding: 0;
}

.form-value {
  flex: 1;
  font-size: 16px;
  color: #999;
}
</style>